package com.superjson.showpro.dao.impl;

import com.superjson.showpro.base.GenericDaoImpl;
import com.superjson.showpro.dao.ArticleCatalogUserDao;
import com.superjson.showpro.entity.ArticleCatalogUser;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;

import static com.beantools.util.ObjectUtil.isNotNull;


@Repository
public class ArticleCatalogUserDaoImpl extends GenericDaoImpl<ArticleCatalogUser> implements ArticleCatalogUserDao {

    public ArticleCatalogUserDaoImpl() {
        super(ArticleCatalogUser.class);
    }


    @Override
    public Long countClick(Long articleId, Long userId) {
        String sql = "SELECT " +
                " COUNT(DISTINCT id) AS clicks " +
                "FROM " +
                " sp_article_catalog_user " +
                "WHERE " +
                " is_deleted = 0 " +
                (isNotNull(userId) && userId instanceof Long && userId > 0 ? " AND user_id = " + userId : "") +
                (isNotNull(articleId) && articleId instanceof Long && articleId > 0 ? " AND article_catalog_id = " + articleId : "");
        Query query = getSession().createSQLQuery(sql).addScalar("clicks", StandardBasicTypes.LONG);
        return (Long) query.uniqueResult();
    }
}